# -*- coding: utf-8 -*-
#author:信科1901 190320026 海琰
import pandas as pd
import numpy as np
import matplotlib.pyplot
import random
from sklearn import linear_model
from sklearn import svm
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import RandomForestRegressor

def cut(data_data): #导入数据集，返回随机抽取70%和30%数据的两个数据集
    num = len(data_data)
    lst_train = random.sample(range(num), int(num * 0.7))
    lst_test = [item for item in range(num)]
    for item1 in lst_train:
        for item2 in lst_test:
            if item1 == item2:
                lst_test.remove(item2)
    train_data = pd.concat([data_data.iloc[[i]] for i in lst_train], ignore_index=True)
    test_data = pd.concat([data_data.iloc[[i]] for i in lst_test], ignore_index=True)
    return train_data,test_data

data_data = pd.read_excel('违禁品识别率(实验数据).xlsx') # 用pd.read_excel导入数据集为data_data
new_data = pd.read_excel('新表.xlsx') # 用pd.read_excel导入数据集为new_data
train_data,test_data = cut(new_data) # 分割数据集
X = np.array(train_data.iloc[:,[3,4]]).reshape(len(train_data.iloc[:,[2]]),2) # 形如[[ai,bi]]的由A、B类元素组成的矩阵
Y = np.array(train_data.iloc[:,[2]]).reshape(len(train_data.iloc[:,[2]]),1) # 成绩
X_test = np.array(test_data.iloc[:,[3,4]]).reshape(len(test_data.iloc[:,[2]]),2) # 测试集识别率
Y_test = np.array(test_data.iloc[:,[2]]).reshape(len(test_data.iloc[:,[2]]),1) # 测试集的成绩

def bar(dataframe): # 导入数据集绘制柱状图
    x = ['Gunw','Explo','Ammo','Firew','LimitT','Dan','Fire','HardT','SharpT','Tools','Others']
    y = []
    train_data,test_data = cut(data_data)
    for i in range(7,18):
        y.append(round(np.average(train_data.iloc[:,[i]]),2))
    matplotlib.pyplot.bar(x, y, width=0.75, align="center", label="Rate")
    matplotlib.pyplot.title("Avg rate", loc="center")
    for a, b in zip(x, y):
        matplotlib.pyplot.text(a, b, b, ha='center', va="bottom", fontsize=12)
    matplotlib.pyplot.xlabel('Sort')
    matplotlib.pyplot.ylabel('Rate')
    matplotlib.pyplot.legend()
    matplotlib.pyplot.show()

def linear (X,Y,X_test,Y_test): # 输入X、Y，输出拟合后的图像与原点成像对比,并输出拟合的准确度
    matplotlib.pyplot.subplot(projection='3d')
    regr = linear_model.LinearRegression()
    regr.fit(X, Y)
    k, b = regr.coef_, regr.intercept_
    x1 = np.linspace(0, 1, 10)
    x2 = np.linspace(0, 1, 10)
    y = x1 * k[0][0] + x2 * k[0][1] + b
    fig = matplotlib.pyplot.figure()
    ax = Axes3D(fig)
    ax.scatter(X[:, 0], X[:, 1], Y[:, 0])
    matplotlib.pyplot.plot(x1, x2, y)
    ax.set_xlim(0, 1)
    ax.set_ylim(0, 1)
    ax.set_zlim(0, 100)
    ax.set_xlabel('X1 axis')
    ax.set_ylabel('X2 axis')
    ax.set_zlabel('Y axis')
    matplotlib.pyplot.show()

    #准确率计算
    accu_rate = []
    for i in range(len(X_test)):
        a= X_test[i][0] * k[0][0] + X_test[i][1] * k[0][1] + b
        accu_rate.append((Y_test[i][0]-abs(a-Y_test[i][0])/Y_test[i][0])) # 准确率
    print("准确率为",round(np.average(accu_rate),4),"%(保留四位小数。)")

def SVR (X,Y,X_test,Y_test):
    regr = svm.SVR(kernel='poly')
    regr.fit(X, Y)
    X_predict = regr.predict(X_test)

    # 准确率计算
    accu_rate = []
    for i in range(len(X_predict)):
        accu_rate.append(Y_test[i][0]-abs(X_predict[i]-Y_test[i][0])/Y_test[i][0]) # 准确率
    print("准确率为",round(np.average(accu_rate),4),"%(保留四位小数。)")

def RandomForest(X,Y,X_test,Y_test):
    rfr = RandomForestRegressor(n_estimators=100, random_state=0)
    rfr.fit(X, Y)
    print("训练的准确率：", rfr.score(X, Y))  # 训练的准确率
    print("测试的准确率：", rfr.score(X_test, Y_test))  # 测试的准确率
    X_predict = rfr.predict(X_test)

    # 准确率计算
    accu_rate = []
    for i in range(len(X_predict)):
        accu_rate.append(Y_test[i][0] - abs(X_predict[i] - Y_test[i][0]) / Y_test[i][0])  # 准确率
    print("结果准确率为", round(np.average(accu_rate), 4), "%(保留四位小数。)")


